package main.dialogs;

import com.primavera.PrimaveraException;
import com.primavera.integration.common.DatabaseInstance;
import main.FactageApp;
import main.Primavera.ConfigServerList;
import main.Primavera.ConfigXML;
import main.Primavera.LoginFunctions;
import main.components.GradientPanel;
import main.users.FactageUser;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LoginDialog {

    private char passwordChar;
    public LoginFunctions loginFnc;

    private JDialog dlg;
    private JTextField inputLogin;
    private JPasswordField inputPassword;
    private JComboBox selectDB;
    private static JComboBox listServer;
    public static DefaultComboBoxModel listServerModel;

    public LoginDialog(LoginFunctions loginFunc) {
        this.loginFnc = loginFunc;
        initComponents();
    }

    public LoginDialog() {
        this.loginFnc = null;
        initComponents();
    }

    private void showDBs() {
        selectDB.removeAllItems();
        loginFnc.setConnectionInfo(getConnectionInfo());
        System.out.println("sHost: " + loginFnc.sHost);
        if (loginFnc.sHost != null) {
            if (loginFnc.getDatabaseInstances() != null) {
                DatabaseInstance[] dbInstances = loginFnc.getDatabaseInstances();

                if ((dbInstances == null) || (dbInstances.length == 0)) {
                    JOptionPane.showMessageDialog(dlg, "No database instances were found", "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                for (DatabaseInstance dbInstance : dbInstances) {
                    selectDB.addItem(dbInstance);
                }
            }
        } else {
            selectDB.removeAllItems();
            ConfigServerList configServerList = new ConfigServerList();
            configServerList.openServerList(listServerModel);
        }

    }

    private static LoginFunctions.ConnectionInfo getConnectionInfo() {
        LoginFunctions.ConnectionInfo connInfo = new LoginFunctions.ConnectionInfo();

        ConfigXML configXML = new ConfigXML();
        String[] serverParam = configXML.getChooseConfig(String.valueOf(listServer.getSelectedItem()));

        if (serverParam[0] == null) {
            connInfo = null;
        } else {
            connInfo.sCallingMode = "Remote";
            connInfo.sHost = serverParam[1];
            connInfo.iPort = Integer.parseInt(serverParam[2]);
            connInfo.iRMIServiceMode = 1;
        }
        System.out.println(connInfo);
        return connInfo;
    }

    private LoginFunctions.LoginInfo getLoginInfo() {
        LoginFunctions.LoginInfo loginInfo = new LoginFunctions.LoginInfo();
        loginInfo.sUserName = inputLogin.getText().trim();

        loginInfo.sPassword = new String(inputPassword.getPassword()).trim();
        DatabaseInstance dbi = (DatabaseInstance) selectDB.getSelectedItem();

        if (dbi == null) {
            JOptionPane.showMessageDialog(dlg, "No database instance is selected", "Error", JOptionPane.ERROR_MESSAGE);
            selectDB.requestFocus();
            return null;
        }

        loginInfo.sDatabaseId = dbi.getDatabaseId();

        return loginInfo;
    }

    //region tryToLogin() - попытка входа в Primavera
    private void tryToLogin() {

        loginFnc.setLoginInfo(getLoginInfo());

        if (loginFnc.sUserName.length() == 0) {
            JOptionPane.showMessageDialog(dlg, "Имя пользователя не может быть пустым.", "Ошибка", JOptionPane.ERROR_MESSAGE);
            inputLogin.requestFocus();
            return;
        }

        try {
            loginFnc.login();
        } catch (PrimaveraException e) {
            JOptionPane.showMessageDialog(dlg, "Введеное имя пользователя или пароль не найдено.", "Ошибка", JOptionPane.ERROR_MESSAGE);
            return;
        }

        dlg.dispose();
    }
    //endregion

    //region initComponents() - инициализация компонентов
    private void initComponents() {

            dlg = new JDialog();
            dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dlg.setLayout(new GridBagLayout());
            dlg.setTitle("Factage");
            dlg.setResizable(false);
            dlg.setType(java.awt.Window.Type.UTILITY);
            dlg.setModal(true);

            GradientPanel headerPanel;
            JLabel headerLabel;

            if (loginFnc != null) {
                headerPanel = new GradientPanel(new GridBagLayout());
                headerLabel = new JLabel("Вход в Oracle Primavera P6");
            } else {
                headerPanel = new GradientPanel(new GridBagLayout(), new Color(252, 141, 234), new Color(178, 99, 164));
                headerLabel = new JLabel("Вход в систему Factage");
            }

            headerLabel.setFont(new Font("Segoe UI", 0, 18));
            headerLabel.setForeground(Color.WHITE);

            dlg.add(headerPanel, new GridBagConstraints(0, 0, 3, 1, 1.0, 0.1, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
            headerPanel.add(headerLabel, new GridBagConstraints(0, 0, 1, 1, 0.5, 0, GridBagConstraints.WEST, GridBagConstraints.WEST, new Insets(30, 56, 7, 56), 0, 0));

            dlg.add(new JLabel("Логин"), new GridBagConstraints(0, 1, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(31, 56, 0, 0), 0, 0));
            dlg.add(new JLabel("Пароль"), new GridBagConstraints(0, 2, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(22, 56, 0, 0), 0, 0));

            if (loginFnc != null) {
                dlg.add(new JLabel("Сервер"), new GridBagConstraints(0, 3, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(22, 56, 0, 0), 0, 0));
                dlg.add(new JLabel("База данных"), new GridBagConstraints(0, 4, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(22, 56, 0, 0), 0, 0));

                inputLogin = new JTextField("Ваш логин Primavera");
                inputLogin.setPreferredSize(new Dimension(183, 22));
                inputLogin.addFocusListener(new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent focusEvent) {
                        inputLogin.setForeground(Color.black);
                        if (inputLogin.getText().equals("Ваш логин Primavera")){
                            inputLogin.setText("");
                        }
                    }
                    @Override
                    public void focusLost(FocusEvent focusEvent) {
                        if (inputLogin.getText().equals("")){
                            inputLogin.setForeground(Color.gray);
                            inputLogin.setText("Ваш логин Primavera");
                        }

                    }
                });

                inputPassword = new JPasswordField("Ваш пароль Primavera");
                inputPassword.setPreferredSize(new Dimension(183, 22));
                inputPassword.addFocusListener(new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent focusEvent) {
                        inputPassword.setForeground(Color.black);
                        if (new String(inputPassword.getPassword()).equals("Ваш пароль Primavera")) {
                            inputPassword.setEchoChar(passwordChar);
                            inputPassword.setText("");
                        }
                    }

                    @Override
                    public void focusLost(FocusEvent focusEvent) {
                        if (new String(inputPassword.getPassword()).equals("")) {
                            inputPassword.setEchoChar((char) 0);
                            inputPassword.setForeground(Color.gray);
                            inputPassword.setText("Ваш пароль Primavera");
                        }

                    }
                });
                inputPassword.addKeyListener(new KeyAdapter() {
                    public void keyPressed(java.awt.event.KeyEvent evt) {
                        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                            tryToLogin();
                        }
                    }
                });
            } else {
                inputLogin = new JTextField("Ваш логин Factage");
                inputLogin.setPreferredSize(new Dimension(183, 22));
                inputLogin.addFocusListener(new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent focusEvent) {
                        inputLogin.setForeground(Color.black);
                        if (inputLogin.getText().equals("Ваш логин Factage")){
                            inputLogin.setText("");
                        }
                    }
                    @Override
                    public void focusLost(FocusEvent focusEvent) {
                        if (inputLogin.getText().equals("")){
                            inputLogin.setForeground(Color.gray);
                            inputLogin.setText("Ваш логин Factage");
                        }

                    }
                });

                inputPassword = new JPasswordField("Ваш пароль Factage");
                inputPassword.setPreferredSize(new Dimension(183, 22));
                inputPassword.addFocusListener(new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent focusEvent) {
                        inputPassword.setForeground(Color.black);
                        if (new String(inputPassword.getPassword()).equals("Ваш пароль Factage")) {
                            inputPassword.setEchoChar(passwordChar);
                            inputPassword.setText("");
                        }
                    }

                    @Override
                    public void focusLost(FocusEvent focusEvent) {
                        if (new String(inputPassword.getPassword()).equals("")) {
                            inputPassword.setEchoChar((char) 0);
                            inputPassword.setForeground(Color.gray);
                            inputPassword.setText("Ваш пароль Factage");
                        }

                    }
                });
                inputPassword.addKeyListener(new KeyAdapter() {
                    public void keyPressed(java.awt.event.KeyEvent evt) {
                        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                            factageLogin();
                        }
                    }
                });
            }

            inputLogin.setForeground(Color.gray);
            inputLogin.addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyPressed(java.awt.event.KeyEvent evt) {
                    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                        inputPassword.requestFocus();
                    }
                }
            });
            dlg.add(inputLogin, new GridBagConstraints(1, 1, 2, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(28, 8, 0, 56), 0, 0));

            this.passwordChar = inputPassword.getEchoChar();
            inputPassword.setEchoChar((char)0);
            inputPassword.setForeground(Color.gray);
            dlg.add(inputPassword, new GridBagConstraints(1, 2, 2, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 56), 0, 0));

            if (loginFnc != null) {
                    ConfigXML configXML = new ConfigXML();
                    listServerModel = configXML.serverListBoxModel();
                    listServer = new JComboBox(listServerModel);
                    listServer.setPreferredSize(new Dimension(150, 22));
                    listServer.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            showDBs();
                        }
                    });
                    dlg.add(listServer, new GridBagConstraints(1, 3, 1, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 0), 0, 0));

                    JButton xmlConfigButton = new JButton();
                    xmlConfigButton.setPreferredSize(new Dimension(24, 24));
                    xmlConfigButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            ConfigServerList configServerList = new ConfigServerList();
                            configServerList.openServerList(listServerModel);
                        }
                    });
                    xmlConfigButton.setIcon(new ImageIcon(getClass().getResource("configButton_grey.png")));
                    dlg.add(xmlConfigButton, new GridBagConstraints(2, 3, 1, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 56), 0, 0));

                    selectDB = new javax.swing.JComboBox();
                    selectDB.setPreferredSize(new Dimension(182, 24));
                    selectDB.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
                    dlg.add(selectDB, new GridBagConstraints(1, 4, 2, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 0), 0, 0));


                    JButton okButton = new JButton("Вход");
                    okButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            tryToLogin();
                        }
                    });
                    okButton.setPreferredSize(new Dimension(90, 24));
                    dlg.add(okButton, new GridBagConstraints(1, 5, 2, 1, 0, 50, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 30, 0), 0, 0));

                    JButton cancelButton = new JButton("Отмена");
                    cancelButton.setPreferredSize(new Dimension(90, 24));
                    dlg.add(cancelButton, new GridBagConstraints(1, 5, 2, 1, 0, 50, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 102, 30, 56), 0, 0));
                    cancelButton.addActionListener(new AbstractAction() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            dlg.dispose();
                        }
                    });

                    showDBs();
            } else {

                JButton okButton = new JButton("Вход");
                okButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        factageLogin();
                    }
                });
                okButton.setPreferredSize(new Dimension(90, 24));
                dlg.add(okButton, new GridBagConstraints(1, 3, 2, 1, 0, 50, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 30, 0), 0, 0));

                JButton cancelButton = new JButton("Отмена");
                cancelButton.setPreferredSize(new Dimension(90, 24));
                dlg.add(cancelButton, new GridBagConstraints(1, 3, 2, 1, 0, 50, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 102, 30, 56), 0, 0));
                cancelButton.addActionListener(new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        dlg.dispose();
                    }
                });

            }

            dlg.pack();

            Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
            dlg.setLocation(screensize.width / 2 - dlg.getWidth() / 2, screensize.height / 2 - dlg.getHeight() / 2);

        if (loginFnc == null || loginFnc.getDatabaseInstances() != null) {
            dlg.setVisible(true);
        }
    }
    //endregion

    //region factageLogin() - попытка входа в Фактаж
    private void factageLogin() {
        if (inputLogin.getText().trim().equals("") || inputLogin.getText().trim().equals("Ваш логин Factage")) {
            JOptionPane.showMessageDialog(dlg, "Поле \"Логин\" не может быть пустым.", "Ошибка", JOptionPane.ERROR_MESSAGE);
            inputLogin.requestFocus();
            return;
        }

        if (new String(inputPassword.getPassword()).trim().equals("") || new String(inputPassword.getPassword()).trim().equals("Ваш пароль Factage")) {
            JOptionPane.showMessageDialog(dlg, "Поле \"Пароль\" не может быть пустым.", "Ошибка", JOptionPane.ERROR_MESSAGE);
            inputPassword.requestFocus();
            return;
        }

        FactageUser user = new FactageUser(inputLogin.getText().trim(), new String(inputPassword.getPassword()).trim());

        if (user.getRoleId() == null) {
            JOptionPane.showMessageDialog(dlg, "Введеное имя пользователя или пароль не найдено.", "Ошибка", JOptionPane.ERROR_MESSAGE);
            return;
        }

        FactageApp.user = user;
        dlg.dispose();

    }
    //endregion

}
